<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;
use app\common\service\RedisService;

/**
 * @ControllerAnnotation(title="用户")
 */
class Usertree extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\User();

    }

    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }

            $admin = session('admin');//
            $param = [];
            if (!empty($admin['uid'])) {
                $param['bucket_id'] = $admin['uid'];
            }

            $count = $this->model->where($param)->count();
            $list = $this->model->where($param)->order($this->sort)->select();

            $data = [
                'code' => 0,
                'msg' => '',
                'count' => $count,
                'data' => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    public function getFansOrderStatisticsByUser($uid)
    {

//        $admin = session('admin');//
//        $uid =  $admin['uid'];
        // $uid =  362245;
        // 考虑性能，数据量不大了时取出全部用户，在内存中操作"
        $sql = "SELECT id , nickname, level1_recommender, level2_recommender, roles FROM sy_user WHERE state > -1";
        $users = Db::query($sql, []);
        $uids[] = $uid;

        $uids = getRecursionUids($uids, $users);
        $sql = "SELECT a.*, b.code as 'goods_name', b.name as 'goods_name', c.nickname as 'buy_nickname', c.phone as 'buy_phone', c.avatar as 'buy_avatar', d.nickname as 'sale_nickname', d.phone as 'sale_phone', d.avatar as 'sale_avatar' FROM sy_user_order a 
    INNER JOIN sy_goods_rush b ON a.gid=b.id
    LEFT JOIN sy_user c ON c.id=a.uid 
    LEFT JOIN sy_user d ON d.id=a.saler_id
    WHERE a.uid IN (" . implode(',', $uids) . " ) AND a.pay_state > -1 AND a.state > -1 AND TO_DAYS(a.create_time) = TO_DAYS(NOW()) ORDER BY a.create_time DESC";
        //测试暂时把这个条件屏蔽 上线要打开
        //AND TO_DAYS(a.create_time) = TO_DAYS(NOW())";
        $results = Db::query($sql, []);
//       var_dump($results);die;
        $topUserStatics = array();
        foreach ($results as $rv) {
            $topUser = [];
            if (!empty($rv) && !empty($rv['uid'])) {
                $curKey = array_search($rv['uid'], array_column($users, 'id'));
                $curUser = array();
                if (!empty($curKey)) {
                    $curUser = $users[$curKey];
                }
                $roles = [];
                if (!empty($curUser) && !empty($curUser['roles'])) {
                    $roles = json_decode($curUser['roles'], true);
                }
                // 只有非管理员有总销
                if (!in_array(1, $roles)) {
                    // 先从统计数据中取值
                    if (empty($topUserStatics[$rv['uid']])) {
                        $curLinks = [$rv['uid']];
                        $curLinks = getRecommendLinks($curLinks, $users);
                        $curTopUser = array_filter($users, function ($item) use ($curLinks) {
                            if ($item['id'] == $curLinks[count($curLinks) - 1]) {
                                return $item;
                            }
                        });
                        if (!empty($curTopUser)) {
                            $curTopUser = array_pop($curTopUser);
                        } else {
                            $curTopUser = [];
                        }
                        // 避免重复计算，将数据缓存至统计数据中
                        $topUserStatics[$rv['uid']] = $curTopUser;
                        $topUser = $curTopUser;
                    }
                }
            }
            $rv['总销'] = $topUser;
        }
        $today_total = 0;
        foreach ($results as $v) {
            $today_total += $v['g_price'];
        }
        $result_data = [
            'list' => $results,
            'today_total' => $today_total
        ];
        // dump($result_data);die;
        // $data = [
        //     'code' => 0,
        //     'msg' => '请指定要查询的用户',
        //     'count' => 0,
        //     'data' => $result_data,
        // ];
        // $this->result_ok('ok',$data);
        return $result_data;
    }


    //粉丝数据
    public function fans($id)
    {
        //获取订单信息
        $orders = $this->getFansOrderStatisticsByUser($id);

        //场次获取
        $admin = session('admin');//
        $param = [];
        if (!empty($admin['uid'])) {
            $param['bucket_id'] = $admin['uid'];
        }

        $bucket = Db::name("rush_schedule")->where(['state' => 1])->where($param)->select();

        $this->assign("count", count($orders['list']));
        $this->assign("total", $orders['today_total'] / 100);
        $this->assign("orders", $orders['list']);
        $this->assign("bucket", $bucket);
        $this->assign("user_id", $id);
        return $this->fetch();
    }

    //粉丝进场数据
    public function jinchang()
    {
        $id = $this->request->post('jinid');//场次id
        $user_id = $this->request->post('user_id');//用户id
        $jinchang = $this->access($user_id, $id, 1);
        return json($jinchang[0]);
    }

    //粉丝抢购成功数据
    public function buy()
    {
        $id = $this->request->post('buyid');//场次id
        $user_id = $this->request->post('user_id');//用户id
        $buy = $this->access($user_id, $id, 2);

        return json($buy[1]);
    }

    public function access($uid, $changci, $type = 1)
    {
        $uids[] = $uid;
        $users = Db::name("user")->where("state > -1")->field("id, nickname, phone, level1_recommender, level2_recommender, roles")->select()->toArray();
        $uids = getRecursionUids($uids, $users);
        $inList = [];
        $okList = [];
        $uids_cp = array_column($users, null, 'id');
        $alldata = RedisService::select(3)->hKeys(self::KEYS['LOG_SCHEDULE'] . $changci);
        $allOkdata = RedisService::select(3)->hKeys(self::KEYS['LOG_SCHEDULE_RUSH_OK'] . $changci);
        foreach ($alldata as $av) {
            $id = (int)$av;
            if (in_array($id, $uids)) {
                $user = $uids_cp[$id] ?? [];
                if (!empty($user)) {
                    $inList[] = ['uid' => $user['id'], 'nickname' => $user['nickname'], 'phone' => $user['phone']];
                }
            }
        }
        foreach ($allOkdata as $av) {
            $id = (int)$av;
            if (in_array($id, $uids)) {
                $user = $uids_cp[$id] ?? [];
                if (!empty($user)) {
                    $okList[] = ['uid' => $user['id'], 'nickname' => $user['nickname'], 'phone' => $user['phone']];
                }
            }
        }
        return [$inList, $okList, $uids];
    }

    //查看支付凭证
    public function payimg()
    {
        $orderid = $this->request->get('orderid');

        $info = Db::name("user_order_payimg")->where(['order_id' => $orderid])->find();
        $this->assign("info", $info);
        return $this->fetch();
    }

    //查看商品信息
    public function getgoods()
    {
        $goodsid = $this->request->get('goods');

        $info = Db::name("goods_rush")->where(['id' => $goodsid])->find();

        $this->assign("info", $info);
        return $this->fetch();
    }

    //查看用户信息
    public function getuser()
    {
        $userid = $this->request->get('userid');
        $info = Db::name("user")->where(['id' => $userid])->find();

        $this->assign("info", $info);
        return $this->fetch();
    }

}